package com.txhy.certificatechain.ui.activity.pay;

import android.Manifest;
import android.app.Dialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.ninetripods.aopermission.permissionlib.annotation.NeedPermission;
import com.txhy.certificatechain.R;
import com.txhy.certificatechain.api.UrlAddress;
import com.txhy.certificatechain.model.bean.BackUserInfoBean;
import com.txhy.certificatechain.model.bean.CardBean;
import com.txhy.certificatechain.model.bean.UserBean;
import com.txhy.certificatechain.presenter.pay.TransPresenter;
import com.txhy.certificatechain.ui.activity.base.BaseActivity;
import com.txhy.certificatechain.ui.manager.ImageLoaderManager;
import com.txhy.certificatechain.ui.view.pay.TransView;
import com.txhy.certificatechain.ui.view.user.FingerView;
import com.txhy.certificatechain.ui.widget.RoundImageView;
import com.txhy.certificatechain.utils.CommUtils;
import com.txhy.certificatechain.utils.FingerCheckUtils;
import com.txhy.certificatechain.utils.GsonUtil;
import com.txhy.certificatechain.utils.LogUtil;
import com.txhy.certificatechain.utils.PrefUtil;
import com.txhy.certificatechain.utils.ToastUtil;
import com.txhy.certificatechain.utils.UIUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2014-2016, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: TransferActivity.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 转账页
 * 创建时间: 2018/9/21 11:45
 * 更新时间：2018/9/21 11:45
 * -----------------------------------------------------------------
 * 2018/9/21 11:45 : 创建 TransferActivity.java (侯建军);
 * -----------------------------------------------------------------
 */
public class TransferActivity extends BaseActivity<TransView, TransPresenter> implements TransView, FingerView {
    @BindView(R.id.img_heard)
    RoundImageView img_heard;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_bankName)
    TextView tv_bankName;
    @BindView(R.id.ll_pay)
    LinearLayout ll_pay;

    @BindView(R.id.view_pay)
    View view_pay;

    @BindView(R.id.ed_money)
    EditText ed_money;
    @BindView(R.id.ed_msg)
    EditText ed_msg;
    private String payType, qrCode, otherId, belongType, money, bankNum,reveReason;
    private UserBean.DataEntity.MapEntity user;

    private UserBean userBean;
    private BackUserInfoBean backUserInfoBean;

    private OptionsPickerView pvCustomOptions;
    FingerCheckUtils fingerCheckUtils;

    private Double jyb, xinyong, diya, yinhang;
    private BigDecimal fuwu;

    @Override
    protected TransPresenter createPresenter() {
        return new TransPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_transfer;
    }

    @Override
    public void initView() {
        super.initView();
        user = PrefUtil.getUserBean(TransferActivity.this);
        userBean = PrefUtil.getUserString(TransferActivity.this);
        payType = getIntent().getStringExtra("payType");
        qrCode = getIntent().getStringExtra("qrCode");
        otherId = getIntent().getStringExtra("otherId");
        belongType = getIntent().getStringExtra("belongType");
        money = getIntent().getStringExtra("money");
        reveReason=getIntent().getStringExtra("reveReason");

        fingerCheckUtils = new FingerCheckUtils(TransferActivity.this, TransferActivity.this);
        mPresenter.backUser(qrCode, otherId, user.getId() + "", belongType, user.getUserType());
    }


    @OnClick({R.id.im_left, R.id.tv_next, R.id.ll_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.im_left:
                finish();
                break;
            case R.id.tv_next:
                if (TextUtils.isEmpty(ed_money.getText().toString())) {
                    ToastUtil.showLong(TransferActivity.this, "您输入的金额不能为空");
                } else {
                    showErCodeDialog();
                }

                break;
            case R.id.ll_pay:
                pvCustomOptions.show();

                break;
        }
    }

    @Override
    public void showProgress(String tipString) {
        showWaitingDialog(tipString);
    }

    @Override
    public void hideProgress() {
        hideWaitingDialog();
    }

    @Override
    public void paySuccess(String msg) {
        LogUtil.e("1111",msg);
        backUserInfoBean = GsonUtil.GsonToBean(msg, BackUserInfoBean.class);
        ImageLoaderManager.LoadImage(TransferActivity.this, UrlAddress.IMGBASE_URL+backUserInfoBean.getData().getReveAccount().getAvatar(), img_heard);
        tv_name.setText(backUserInfoBean.getData().getReveAccount().getCardName());
        switch (backUserInfoBean.getData().getReveAccount().getBelongType()) {
            case 0:
                tv_type.setText("个人");
                break;
            case 1:
                tv_type.setText("企业");
                break;
        }
        initCustomOptionPicker("选择银行卡");
        initEditMoney();
        if (money.equals("0")) {

        } else {
            ed_money.setFocusable(false);
            ed_money.setText(money);
            setMoney();
        }
    }

    @Override
    public void payFail(String msg) {
        finish();
        ToastUtil.showLong(TransferActivity.this, msg);
    }

    @Override
    public void fingerSuccess(String msg) {
        mPresenter.endPay(otherId, ed_money.getText() + "",  payBean.getPayJyb() + "", payBean.getPayCredit() + "", payBean.getPayPawn() + "",
                yinhang + "", fuwu.toString(), bankNum, payBean.getUserId() + "", backUserInfoBean.getData().getReveAccount().getBelongType() + "", payBean.getBelongType() + "",reveReason,ed_msg.getText()+"");
    }

    @Override
    public void fingerFail(String msg) {
        ToastUtil.showLong(TransferActivity.this, msg);
    }


    //最终的付款
    @Override
    public void endPaySuccess(String msg) {
        ToastUtil.showLong(TransferActivity.this, msg);
        finish();
    }

    @Override
    public void endPayFail(String msg) {
        ToastUtil.showLong(TransferActivity.this, msg);
    }

    BackUserInfoBean.DataEntity.PayAccoutEntity payBean;

    private void initEditMoney() {
        payBean = backUserInfoBean.getData().getPayAccout();


        ed_money.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        ed_money.setText(s);
                        ed_money.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    ed_money.setText(s);
                    ed_money.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        ed_money.setText(s.subSequence(0, 1));
                        ed_money.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                ll_pay.setVisibility(View.GONE);
                view_pay.setVisibility(View.GONE);
                if (TextUtils.isEmpty(ed_money.getText().toString())) {
                    return;
                }
                setMoney();
            }
        });
    }


    private void initCustomOptionPicker(String title) {
        getData();
        tv_bankName.setText(cardList.get(0).getCardNo());
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置

                bankNum = cardList.get(options1).getId();
                tv_bankName.setText(cardList.get(options1).getPickerViewText());

            }
        })
                .setSubmitColor(UIUtils.getColor(R.color.ed584c))//确定按钮文字颜色
                .setCancelColor(UIUtils.getColor(R.color.text666))//取消按钮文字颜色
                .setTitleText(title)//标题文字
                .build();
        pvCustomOptions.setPicker(cardList);//添加数据
    }

    private List<CardBean> cardList = new ArrayList<CardBean>();

    private void getData() {
        for (int i = 0; i < backUserInfoBean.getData().getPayAccout().getBankInfo().size(); i++) {
            cardList.add(new CardBean(backUserInfoBean.getData().getPayAccout().getBankInfo().get(i).getBankNo(), backUserInfoBean.getData().getPayAccout().getBankInfo().get(i).getBelongBank()));
        }

    }
    private Dialog mDialog;

    /**
     * 二维码提示dialog
     * @return
     */
    public Dialog showErCodeDialog() {
        hideErCodeDialog();
        mDialog = new Dialog(TransferActivity.this, R.style.MyDialog);
        LinearLayout root = (LinearLayout) LayoutInflater.from(TransferActivity.this).inflate(
                R.layout.item_paymoney, null);
        TextView tv_allMoney = root.findViewById(R.id.tv_allMoney);
        TextView tv_bankItem = root.findViewById(R.id.tv_bankName);
        TextView tv_jyb = root.findViewById(R.id.tv_jyb);
        TextView tv_xinyong = root.findViewById(R.id.tv_xinyong);
        TextView tv_diya = root.findViewById(R.id.tv_diya);
        TextView tv_yinhang = root.findViewById(R.id.tv_yinhang);
        TextView tv_fuwu = root.findViewById(R.id.tv_fuwu);

        tv_allMoney.setText(ed_money.getText().toString());
        tv_bankItem.setText(tv_bankName.getText().toString());
        tv_jyb.setText(jyb + "");
        tv_xinyong.setText(xinyong + "");
        tv_diya.setText(diya + "");
        tv_yinhang.setText(yinhang + "");
        tv_fuwu.setText("+" + fuwu + "(服务费)");

        root.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideErCodeDialog();
            }
        });
        root.findViewById(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (PrefUtil.getPayType(TransferActivity.this)) {
                    case 0:
                        fingerCheckUtils.showFingerDialog();
                        break;
                    case 1:
                        startActicity(userBean.getData().getPhone(), "1");
                        break;
                    case 2:
                        fingerCheckUtils.showFingerDialog();
                        break;
                    case 3:
                        break;
                }
                hideErCodeDialog();
            }
        });
        mDialog.setContentView(root);
        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        mDialog.setCancelable(true);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        lp.width = ((int) getResources().getDisplayMetrics().widthPixels) - 280; // 宽度
        root.measure(0, 0);
        lp.height = root.getMeasuredHeight();
        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mDialog.show();
        return mDialog;
    }

    /**
     * 隐藏二维码提示
     */
    public void hideErCodeDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    /**
     * 设置金额
     */
    private void setMoney() {
        BigDecimal moneyPay = new BigDecimal(ed_money.getText().toString());
        BigDecimal moneyNum = moneyPay.add(CommUtils.calServiceFee(moneyPay, payBean.getServiceMoney()));
        fuwu = CommUtils.calServiceFee(moneyPay, payBean.getServiceMoney());
        if (moneyNum.compareTo(BigDecimal.valueOf(payBean.getPayJyb())) != 1) {
            jyb = moneyNum.doubleValue();
            xinyong = 0.0;
            diya = 0.0;
            yinhang = 0.0;
        } else if (moneyNum.subtract(BigDecimal.valueOf(payBean.getPayJyb())).compareTo(BigDecimal.valueOf(payBean.getPayCredit())) != 1) {
            jyb = payBean.getPayJyb();
            xinyong = (moneyNum.subtract(BigDecimal.valueOf(payBean.getPayJyb()))).doubleValue();
            diya = 0.0;
            yinhang = 0.0;
        } else if (moneyNum.subtract(BigDecimal.valueOf(payBean.getPayJyb())).subtract(BigDecimal.valueOf(payBean.getPayCredit())).compareTo(BigDecimal.valueOf(payBean.getPayPawn())) != 1) {
            jyb = payBean.getPayJyb();
            xinyong = payBean.getPayCredit();
            diya = (moneyNum.subtract(BigDecimal.valueOf(payBean.getPayJyb())).subtract(BigDecimal.valueOf(payBean.getPayCredit()))).doubleValue();
            yinhang = 0.0;
        } else {
            jyb = payBean.getPayJyb();
            xinyong = payBean.getPayCredit();
            diya = payBean.getPayPawn();
            yinhang = (moneyNum.subtract(BigDecimal.valueOf(payBean.getPayJyb())).subtract(BigDecimal.valueOf(payBean.getPayCredit())).subtract(BigDecimal.valueOf(payBean.getPayPawn()))).doubleValue();
            ll_pay.setVisibility(View.VISIBLE);
            view_pay.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 指纹识别结果
     * @param result
     */
    @Override
    public void getFingerResult(int result) {
        switch (result) {
            case 1:
                fingerCheckUtils.hideFingerDialog();
                switch (PrefUtil.getPayType(TransferActivity.this)) {
                    case 0://指纹
                        mPresenter.toFingerLogin(userBean.getData().getPhone(), CommUtils.getIMEI(TransferActivity.this), "0", "");
                        break;
                    case 2://指纹人脸
                        startActicity(userBean.getData().getPhone(), "2");
                        break;
                }
                break;
        }
    }

    /**
     * 启动人脸识别
     * @param phone
     * @param type
     */
    @NeedPermission(value = {Manifest.permission.CAMERA}, requestCode = 0)
    private void startActicity(String phone, String type) {
//        Intent intent = new Intent(TransferActivity.this, FaceDetectExpActivity.class);
//        intent.putExtra("phone", phone);
//        intent.putExtra("type", type);
//        intent.putExtra("activity", MainActivity.class);
//        intent.putExtra("gongneng", "1");//0是登录 1是支付
//
//        //支付所需参数的拼接
//        intent.putExtra("reveUserId", otherId);
//        intent.putExtra("money", ed_money.getText() + "");
//        intent.putExtra("jyb", payBean.getPayJyb() + "");
//        intent.putExtra("validCredit", payBean.getPayCredit() + "");
//        intent.putExtra("validPawn", payBean.getPayPawn() + "");
//        intent.putExtra("bankMoney", yinhang+"");
//        intent.putExtra("serviceMoney", fuwu.toString());
//        intent.putExtra("bankCard", bankNum);
//        intent.putExtra("payUserId", payBean.getUserId() + "");
//        intent.putExtra("reveBelongType", backUserInfoBean.getData().getReveAccount().getBelongType()+"");
//        intent.putExtra("payBelongType", payBean.getBelongType() + "");
//        intent.putExtra("reveReason", reveReason);
//        intent.putExtra("payReason", ed_msg.getText()+"");
//        startActivity(intent);
        finish();
    }
}

